<?php

/**
 * 连接 mysql 数据库
 */


try {
    $config = [
        'host' => '127.0.0.1',
        'user' => 'root',
        'password' => 'root',
        'database' => 'testdb',
        'charset' => 'utf8mb4',
    ];

    $dsn = sprintf("mysql:host=%s;dbname=%s;charset=%s", $config['host'], $config['database'], $config['charset']);

    // 设置
    $options = [
        // PDO::ATTR_PERSISTENT => true, // 持久化连接
    ];
    $pdo = new PDO($dsn, $config['user'], $config['password'], $options);

    // 设置错误处理方式 > 抛出异常
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    /**
     * 操作
     */
    // 查询语句 query
    $query = $pdo->query('SELECT * from t_user');

    $rows = $query->fetchAll(); // 获取数据
    print_r($rows);

    // 执行语句 exec
    // $pdo->exec("insert into t_user (id, name) values (2, 'Joe')");

    // 预处理语句
    // 占位符 : ?
    $sth = $pdo->prepare("SELECT * from t_user where id=:id");
    $sth->execute([':id' => 1]);

    $sth = $pdo->prepare("SELECT * from t_user where id=? and id >=?");
    $sth->execute([1, 2]);

    $sth = $pdo->prepare("insert into t_user (id, name) values (2, 'Joe')");
    echo $pdo->lastInsertId(); // 获取最后一条执行插入sql返回的自增id


    // 事务
    try {
        $pdo->beginTransaction();

        // $pdo->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
        // $pdo->exec("insert into salarychange (id, amount, changedate) values (23, 50000, NOW())");

        $pdo->commit();
    } catch (Exception $e) {
        $pdo->rollBack();
        echo "Failed: " . $e->getMessage();
    }


} catch (PDOException $e) {
    die('Exception:' . $e->getMessage());
}


